package com.chinaoct.siku.util;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;


/**
 * Jaxb工具类
 * @author macrotea@qq.com
 * @since 2014-10-29 上午10:19
 */
public class JaxbUtil {

    private static Logger logger = LoggerFactory.getLogger(JaxbUtil.class);

	/**
	 * JavaBean转换成XML
	 * @param obj
	 * @param encoding 
	 * @return 
	 */
	public static String bean2xml(Object obj, String encoding) {
		String result = null;
		try {
			JAXBContext context = JAXBContext.newInstance(obj.getClass());
			Marshaller marshaller = context.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);

			StringWriter writer = new StringWriter();
			marshaller.marshal(obj, writer);
			result = writer.toString();
		} catch (Exception e) {
            logger.error("JavaBean转换成XML", e);
		}

		return result;
	}

    /**
     * XML转换成Bean
     * @param xml
     * @param c
     * @param <T>
     * @return
     */
	@SuppressWarnings("unchecked")
	public static <T> T xml2bean(String xml, Class<T> c) {
		if(StringUtils.isEmpty(xml)) {
			return null;
		}
		T t = null;
		try {
			xml=transferred(xml);
			JAXBContext context = JAXBContext.newInstance(c);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			t = (T) unmarshaller.unmarshal(new StringReader(xml));
		} catch (Exception e) {
            logger.error("JavaBean转换成XML", e);
        }

		return t;
	}
	
	public static String transferred(String xml){
		    if(!StringUtils.isEmpty(xml)) {
				xml=xml.replace("&", "&amp;");
		    }
			return xml;
	}
	
//	public static String xml2json(String xmlString) {
//		XMLSerializer xmlSerializer = new XMLSerializer();
//		JSON jsonObj = xmlSerializer.read(xmlString);
//		String jsonStr = jsonObj.toString();
//	    jsonStr = jsonStr.replace("[]", "\"\"");
//	    return jsonStr;
//    }
}
